<template>
  <div class="user-profile-container">
    <!-- 统一白色背景的个人中心 -->
    <div class="profile-content">
      <!-- 用户信息 -->
      <div class="user-info-section">
        <div class="avatar-section">
          <el-avatar :size="60" :src="userAvatar" class="user-avatar">
            <el-icon :size="30"><User /></el-icon>
          </el-avatar>
          <div class="user-details">
            <h2>{{ currentUser?.username || '用户' }}</h2>
            <p class="user-email">{{ currentUser?.email || '暂无邮箱信息' }}</p>
            <div class="user-points">积分: {{ userStore.userPoints !== undefined && userStore.userPoints !== null ? userStore.userPoints : 0 }} <el-tooltip content="当前可用积分，可通过签到、完成题目等方式获得" placement="right"><el-icon><QuestionFilled /></el-icon></el-tooltip></div>
          </div>
        </div>
        <div class="user-actions">
          <el-button 
            v-if="!checkedInToday && isLoggedIn" 
            type="primary" 
            size="small" 
            class="checkin-button" 
            @click="handleCheckin">
            签到
          </el-button>
          <el-button 
            v-else-if="isLoggedIn" 
            type="success" 
            size="small" 
            class="checkin-button checked-button" 
            disabled>
            已签到
          </el-button>
          <el-button type="primary" @click="editProfile" size="small">编辑资料</el-button>
        </div>
      </div>

      <!-- 签到日历 -->
      <div class="section-content">
        <div class="calendar-header-section">
          <h3>签到日历</h3>
          <div class="calendar-nav">
            <el-button type="text" @click="prevMonth" class="month-arrow">
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
            <span class="current-month">{{ currentYear }}年{{ currentMonth }}月</span>
            <el-button type="text" @click="nextMonth" class="month-arrow">
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
        </div>
        
        <div class="checkin-calendar-section">
          <!-- 星期标题 -->
          <div class="weekdays">
            <div class="weekday" v-for="day in ['日', '一', '二', '三', '四', '五', '六']" :key="day">{{ day }}</div>
          </div>
          
          <!-- 日历日期 -->
          <div class="days-grid">
            <div 
              v-for="day in calendarDays" 
              :key="day.date" 
              class="day-cell"
              :class="{
                'empty': !day.inMonth,
                'checked': day.checkedIn,
                'today': day.isToday,
                'disabled': day.disabled
              }"
            >
              <div v-if="day.inMonth" class="day-content">
                <div class="day-number">{{ day.day }}</div>
                <div v-if="day.checkedIn" class="check-icon">✓</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 签到记录列表 -->
      <div class="section-content">
        <h3>签到记录</h3>
        <el-table :data="paginatedCheckedInRecords" style="width: 100%" size="small" class="checkin-records-table">
          <el-table-column prop="date" label="日期" width="150" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.date) }}
            </template>
          </el-table-column>
          <el-table-column prop="checkedIn" label="签到状态" width="100" align="center">
            <template #default="scope">
              <el-tag type="success">
                已签到
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="points" label="获得积分" width="100" align="center">
            <template #default="scope">
              <span class="points-value">{{ scope.row.points || 0 }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="table-pagination">
          <el-pagination
            small
            layout="prev, pager, next"
            :total="checkedInRecords.length"
            :page-size="5"
            v-model:current-page="currentPage"
            background
          />
        </div>
      </div>

      <!-- 学习统计 -->
      <div class="section-content">
        <h3>学习统计</h3>
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-value">{{ studyDays }}</div>
            <div class="stat-label">连续签到</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ userStore.userPoints !== undefined && userStore.userPoints !== null ? userStore.userPoints : 0 }}</div>
            <div class="stat-label">当前积分 <el-tooltip content="当前可用积分" placement="top"><el-icon size="10"><QuestionFilled /></el-icon></el-tooltip></div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ totalAchievements }}</div>
            <div class="stat-label">已获得成就</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ totalQuestions }}</div>
            <div class="stat-label">总题数</div>
          </div>
        </div>
        
        
      </div>
      
      <!-- 题目完成情况 -->
      <div class="section-content">
        <h3>题目完成情况</h3>
        <div class="module-questions-list">
          <div class="module-question-item" v-for="(count, module, index) in completedQuestions" :key="module">
            <span class="module-name">{{ module }}:</span>
            <span class="module-count">{{ count }} 题</span>
          </div>
        </div>
      </div>
      
      <!-- 学习进度 -->
      <div class="section-content">
        <h3>学习进度</h3>
        <div class="progress-grid">
          <div class="progress-item" v-for="(progress, module) in moduleProgressDisplay" :key="module">
            <div class="module-header">
              <div class="module-name">{{ moduleNameMapping[module] }}</div>
            </div>
            <el-progress 
              :percentage="progress.percentage" 
              :format="percentageFormat" 
              :stroke-width="6" 
              :status="progress.percentage === 100 ? 'success' : ''">
            </el-progress>
            <div class="progress-text">
              {{ progress.completed }} / {{ progress.total }} 题
            </div>
          </div>
        </div>
      </div>
      
      <!-- 成就概览 -->
      <div class="section-content">
        <div class="achievements-header">
          <h3>我的成就</h3>
        </div>
        <div class="achievements-summary">
          <div class="achievement-stats">
            <div class="stat-item">
              <div class="stat-value">{{ totalAchievements }}</div>
              <div class="stat-label">已获得成就</div>
            </div>
          </div>
          
          <div class="all-achievements" v-if="earnedAchievements.length > 0">
            <h4>已获得的成就</h4>
            <div class="achievement-grid">
              <achievement-badge
                v-for="achievement in earnedAchievements"
                :key="achievement.id"
                :id="achievement.id"
                :name="achievement.name"
                :description="achievement.description"
                :icon-url="achievement.iconUrl"
                :earned="achievement.earned"
                :earned-date="achievement.earnedDate"
                :condition-type="achievement.conditionType"
                :condition-value="achievement.conditionValue"
                :points-reward="achievement.pointsReward"
                :points-claimed="achievement.pointsClaimed"
                @points-claimed="handlePointsClaimed"
              />
            </div>
          </div>
          <div v-else class="empty-achievements">
            <el-icon class="empty-icon"><InfoFilled /></el-icon>
            <p>暂无已获得的成就，继续努力吧！</p>
          </div>
        </div>
      </div>
      
    </div>
  </div>

  <!-- 编辑资料对话框 -->
  <el-dialog
    v-model="editDialogVisible"
    title="编辑个人资料"
    width="500px"
    class="apple-style-dialog"
  >
    <el-form
      :model="editForm"
      :rules="editRules"
      ref="editFormRef"
      label-width="80px"
    >
      <!-- 头像上传 -->
      <el-form-item label="头像">
        <div class="avatar-upload-container">
          <el-avatar :size="80" :src="tempAvatarUrl || editForm.avatar" class="avatar-preview">
            <el-icon :size="40"><User /></el-icon>
          </el-avatar>
          <div class="avatar-upload-controls">
            <input 
              ref="avatarInputRef"
              type="file" 
              accept="image/*" 
              style="display: none" 
              @change="handleAvatarFileSelect"
            />
            <el-button size="small" @click="triggerAvatarUpload">选择图片</el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="uploadAvatar" 
              :loading="avatarUploading"
              :disabled="!selectedAvatarFile || avatarUploading"
            >
              上传头像
            </el-button>
          </div>
          <div v-if="selectedAvatarFile" class="file-info">
            已选择: {{ selectedAvatarFile.name }}
          </div>
        </div>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="editForm.username" disabled />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="editForm.nickname" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="editForm.phone" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProfile">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 成就详情对话框 -->
  <el-dialog
    v-model="achievementsDialogVisible"
    title="我的成就"
    width="800px"
    class="apple-style-dialog achievements-dialog"
  >
    <div class="achievements-dialog-content">
      <div class="achievement-stats">
        <div class="stat-item">
          <div class="stat-icon">
            <el-icon><Trophy /></el-icon>
          </div>
          <div>
            <div class="stat-value">{{ totalAchievements }}</div>
            <div class="stat-label">已获得成就</div>
          </div>
        </div>
      </div>
      
      
      <el-tabs v-model="achievementsActiveTab" class="achievement-tabs" type="border-card">
        <el-tab-pane label="已获成就" name="earned">
          <div class="achievement-section">
            <div class="achievement-grid">
              <achievement-badge
                v-for="achievement in earnedAchievements"
                :key="achievement.id"
                :id="achievement.id"
                :name="achievement.name"
                :description="achievement.description"
                :icon-url="achievement.iconUrl"
                :earned="achievement.earned"
                :earned-date="achievement.earnedDate"
                :condition-type="achievement.conditionType"
                :condition-value="achievement.conditionValue"
                :points-reward="achievement.pointsReward"
                :points-claimed="achievement.pointsClaimed"
                @points-claimed="handlePointsClaimed"
              />
            </div>
            <div v-if="earnedAchievements.length === 0" class="empty-state">
              <el-icon><InfoFilled /></el-icon>
              <p>暂无已获得的成就，继续努力吧！</p>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="全部成就" name="all">
          <div class="achievement-section">
            <div class="achievement-grid">
              <achievement-badge
                v-for="achievement in allAchievements"
                :key="achievement.id"
                :id="achievement.id"
                :name="achievement.name"
                :description="achievement.description"
                :icon-url="achievement.iconUrl"
                :earned="achievement.earned"
                :earned-date="achievement.earnedDate"
                :condition-type="achievement.conditionType"
                :condition-value="achievement.conditionValue"
                :points-reward="achievement.pointsReward"
                :points-claimed="achievement.pointsClaimed"
                @points-claimed="handlePointsClaimed"
              />
            </div>
            <div v-if="allAchievements.length === 0" class="empty-state">
              <el-icon><Loading /></el-icon>
              <p>正在加载成就数据...</p>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Calendar, 
  Check, 
  Medal, 
  QuestionFilled, 
  Trophy, 
  User, 
  Flag, 
  Compass, 
  ChatDotRound, 
  DataAnalysis, 
  Finished, 
  TrendCharts,
  Star,
  InfoFilled,
  Loading,
  ArrowLeft,
  ArrowRight
} from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/user';
// @ts-ignore
import AchievementBadge from '@/components/AchievementBadge.vue';
import { getCheckinStatus, userCheckin, getMonthlyCheckinRecords as fetchMonthlyCheckinRecordsApi } from '@/api/checkin';
import { getPoliticsQuestions } from '@/api/politics';
import { getCommonSenseQuestions } from '@/api/commonSense';
import { getLanguageQuestions } from '@/api/language';
import { getQuantityQuestions } from '@/api/quantity';
import { getJudgmentQuestions } from '@/api/judgment';
import { getDataAnalysisQuestions } from '@/api/dataAnalysis';
// @ts-ignore
import { getAchievements, getUserAchievements, claimAchievementPoints as claimAchievementPointsApi } from '@/api/achievement';
import { updateUser } from '@/api/user';
import { uploadImage } from '@/api/upload'; // 添加导入
import type { FormInstance, FormRules } from 'element-plus';

// 初始化用户store和路由
const userStore = useUserStore();
const router = useRouter();

// 用户信息
const currentUser = computed(() => userStore.userInfo);
const isLoggedIn = computed(() => userStore.isLoggedIn);
const userAvatar = computed(() => currentUser.value?.avatar || '');

// 学习统计数据
const studyDays = ref(0);
const checkedInToday = ref(false);
const completedQuestions = ref({
  时政题目: 0,
  常识题目: 0,
  言语题目: 0,
  数量题目: 0,
  判断题目: 0,
  资料题目: 0
});

const totalQuestions = computed(() => {
  return Object.values(completedQuestions.value).reduce((a, b) => a + b, 0);
});

// 头衔系统
const titleConfig = {
  '萌新学徒': { min: 1, max: 10, description: '初探题海的小萌新，保持好奇心！' },
  '青铜思考者': { min: 11, max: 50, description: '逻辑的齿轮开始转动啦~' },
  '白银解题手': { min: 51, max: 100, description: '已能熟练拆解基础难题！' },
  '黄金破题师': { min: 101, max: 200, description: '题目陷阱都逃不过你的眼睛！' },
  '白金智囊': { min: 201, max: 500, description: '解题如行云流水，思路清晰！' },
  '钻石逻辑王': { min: 501, max: 1000, description: '复杂问题也能庖丁解牛！' },
  '星耀学者': { min: 1001, max: 2000, description: '题海中的方法论大师！' },
  '王者题圣': { min: 2001, max: 5000, description: '信手拈来皆是解题套路！' },
  '传奇题神': { min: 5001, max: 10000, description: '题目见你都要瑟瑟发抖！' }
};

const currentTitle = computed(() => {
  const total = totalQuestions.value;
  for (const [title, config] of Object.entries(titleConfig)) {
    if (total >= config.min && total <= config.max) {
      return { title, ...config };
    }
  }
  return { title: '萌新学徒', ...titleConfig['萌新学徒'] };
});

// 模块进度数据
const moduleProgress = ref({
  politics: 0,
  commonSense: 0,
  language: 0,
  quantity: 0,
  judgment: 0,
  dataAnalysis: 0
});

// 模块名称映射
const moduleNameMapping = {
  politics: '时政',
  commonSense: '常识',
  language: '言语',
  quantity: '数量',
  judgment: '判断',
  dataAnalysis: '资料分析'
};

// 模块图标映射
const moduleIcons = {
  politics: Flag,
  commonSense: Compass,
  language: ChatDotRound,
  quantity: DataAnalysis,
  judgment: Finished,
  dataAnalysis: TrendCharts
};

// 模块样式类映射

// 模块进度显示数据
const moduleProgressDisplay = computed(() => {
  const totalQuestionsByModule = {
    politics: 25,
    commonSense: 30,
    language: 20,
    quantity: 15,
    judgment: 18,
    dataAnalysis: 12
  };

  return {
    politics: {
      percentage: moduleProgress.value.politics,
      completed: completedQuestions.value.时政题目,
      total: totalQuestionsByModule.politics
    },
    commonSense: {
      percentage: moduleProgress.value.commonSense,
      completed: completedQuestions.value.常识题目,
      total: totalQuestionsByModule.commonSense
    },
    language: {
      percentage: moduleProgress.value.language,
      completed: completedQuestions.value.言语题目,
      total: totalQuestionsByModule.language
    },
    quantity: {
      percentage: moduleProgress.value.quantity,
      completed: completedQuestions.value.数量题目,
      total: totalQuestionsByModule.quantity
    },
    judgment: {
      percentage: moduleProgress.value.judgment,
      completed: completedQuestions.value.判断题目,
      total: totalQuestionsByModule.judgment
    },
    dataAnalysis: {
      percentage: moduleProgress.value.dataAnalysis,
      completed: completedQuestions.value.资料题目,
      total: totalQuestionsByModule.dataAnalysis
    }
  };
});

// 成就数据
const allAchievements = ref<any[]>([]);
const totalAchievements = ref(0);
const recentAchievements = ref<any[]>([]);



// 格式化进度百分比
const percentageFormat = (percentage: number) => {
  return percentage === 100 ? '完成' : `${percentage}%`;
};

// 获取用户学习数据
const fetchUserStudyData = async () => {
  if (!isLoggedIn.value) return;
  
  try {
    // 获取各模块题目数量
    const [politics, commonSense, language, quantity, judgment, dataAnalysis] = await Promise.all([
      getPoliticsQuestions({ count: true }),
      getCommonSenseQuestions({ count: true }),
      getLanguageQuestions({ count: true }),
      getQuantityQuestions({ count: true }),
      getJudgmentQuestions({ count: true }),
      getDataAnalysisQuestions({ count: true })
    ]);

    completedQuestions.value = {
      时政题目: politics.data.total || 0,
      常识题目: commonSense.data.total || 0,
      言语题目: language.data.total || 0,
      数量题目: quantity.data.total || 0,
      判断题目: judgment.data.total || 0,
      资料题目: dataAnalysis.data.total || 0
    };

    // 计算每个模块的完成进度
    const totalQuestionsByModule = {
      时政题目: 25,
      常识题目: 30,
      言语题目: 20,
      数量题目: 15,
      判断题目: 18,
      资料题目: 12
    };

    moduleProgress.value = {
      politics: Math.round((completedQuestions.value.时政题目 / totalQuestionsByModule.时政题目) * 100),
      commonSense: Math.round((completedQuestions.value.常识题目 / totalQuestionsByModule.常识题目) * 100),
      language: Math.round((completedQuestions.value.言语题目 / totalQuestionsByModule.言语题目) * 100),
      quantity: Math.round((completedQuestions.value.数量题目 / totalQuestionsByModule.数量题目) * 100),
      judgment: Math.round((completedQuestions.value.判断题目 / totalQuestionsByModule.判断题目) * 100),
      dataAnalysis: Math.round((completedQuestions.value.资料题目 / totalQuestionsByModule.资料题目) * 100)
    };

    // 获取连续签到天数和签到状态
    const checkinStatusRes = await getCheckinStatus();
    // @ts-ignore
    if (checkinStatusRes.code === 200) {
      if (checkinStatusRes.data.consecutiveDays !== undefined && checkinStatusRes.data.consecutiveDays !== null) {
        studyDays.value = checkinStatusRes.data.consecutiveDays;
      }
      checkedInToday.value = checkinStatusRes.data.checkedInToday;
    }
  } catch (error) {
    console.error('获取学习数据失败:', error);
    ElMessage.error('获取学习数据失败，请稍后重试');
  }
};

// 获取成就数据
const fetchAchievementsData = async () => {
  if (!isLoggedIn.value) return;
  
  try {
    // 获取用户成就
    const userAchievementsRes = await getUserAchievements();
    console.log('用户成就数据响应:', userAchievementsRes);
    if (userAchievementsRes.code === 200 && userAchievementsRes.data) {
      totalAchievements.value = userAchievementsRes.data.totalCount || 0;
      console.log('总成就数:', totalAchievements.value);
      
      // 获取所有成就定义
      const achievementsRes = await getAchievements();
      if (achievementsRes.code === 200 && achievementsRes.data) {
        // 合并成就定义和用户成就状态
        const userAchievementMap = {};
        // @ts-ignore
        // @ts-ignore
        userAchievementsRes.data.achievements.forEach((ua: any) => {
          // @ts-ignore
          userAchievementMap[ua.achievementId] = ua;
        });
        
        // 修复：使用 achievementsRes.data.list 而不是 achievementsRes.data
        // @ts-ignore
        allAchievements.value = achievementsRes.data.list.map((achievement: any) => {
          // @ts-ignore
          const userAchievement = userAchievementMap[achievement.achievementId];
          return {
            id: userAchievement?.id || achievement.achievementId, // 使用用户成就ID而不是成就ID
            name: achievement.name,
            description: achievement.description,
            iconUrl: achievement.iconUrl,
            category: achievement.category,
            conditionType: achievement.conditionType,
            conditionValue: achievement.conditionValue,
            pointsReward: achievement.pointsReward,
            earned: !!userAchievement,
            earnedDate: userAchievement?.earnedDate || null,
            pointsClaimed: userAchievement?.pointsClaimed || false
          };
        });
        
        // 获取最近获得的成就（按获得时间倒序排列）
        recentAchievements.value = allAchievements.value
          // @ts-ignore
          .filter((a: any) => a.earned)
          // @ts-ignore
          .sort((a: any, b: any) => new Date(b.earnedDate).getTime() - new Date(a.earnedDate).getTime());
      }
    }
  } catch (error) {
    console.error('获取成就数据失败:', error);
    ElMessage.error('获取成就数据失败，请稍后重试');
  }
};

// 扩展DayCell接口以包含积分信息
interface DayCell {
  date: string;
  day: number;
  inMonth: boolean;
  checkedIn: boolean;
  isToday: boolean;
  disabled: boolean;
  points?: number; // 添加积分字段
}

// 添加签到记录列表相关数据
const checkinRecordsList = ref<DayCell[]>([]);
const currentPage = ref(1); // 添加当前页码

// 只显示已签到记录的计算属性
const checkedInRecords = computed(() => {
  return checkinRecordsList.value.filter(record => record.checkedIn);
});

// 分页后的已签到记录
const paginatedCheckedInRecords = computed(() => {
  const start = (currentPage.value - 1) * 5;
  const end = start + 5;
  return checkedInRecords.value.slice(start, end);
});

// 格式化日期显示
const formatDate = (dateStr: string) => {
  if (!dateStr || dateStr.startsWith('empty')) return '';
  const date = new Date(dateStr);
  return date.toLocaleDateString('zh-CN');
};

// 获取用户所有签到记录的新函数
const fetchAllCheckinRecords = async () => {
  try {
    // 获取最近几个月的签到记录，以确保包含最新的签到数据
    const today = new Date();
    const currentYear = today.getFullYear();
    const currentMonth = today.getMonth() + 1;
    
    // 获取当前月和前两个月的签到记录
    const monthsToFetch = [
      { year: currentYear, month: currentMonth },
      { year: currentMonth === 1 ? currentYear - 1 : currentYear, month: currentMonth === 1 ? 12 : currentMonth - 1 },
      { year: currentMonth <= 2 ? currentYear - 1 : currentYear, month: currentMonth <= 2 ? (currentMonth === 1 ? 11 : 12) : currentMonth - 2 }
    ];
    
    // 存储所有已签到的日期和积分信息
    const allCheckedInDates: Record<string, { checked: boolean; points?: number }> = {};
    
    // 获取每个月的签到记录
    for (const { year, month } of monthsToFetch) {
      try {
        const response: any = await getMonthlyCheckinRecords(year, month);
        console.log(`获取${year}年${month}月签到记录响应:`, response); // 添加日志以便调试
        if (response.code === 200 && response.data && response.data.checkinRecords) {
          // 从checkinRecords中提取日期和积分信息
          for (const record of response.data.checkinRecords) {
            const date = record.checkinDate;
            const points = record.pointsEarned || 0;
            allCheckedInDates[date] = {
              checked: true,
              points: points
            };
          }
        }
      } catch (error) {
        console.warn(`获取${year}年${month}月签到记录失败:`, error);
      }
    }
    
    // 将返回的数据转换为DayCell格式
    const records: DayCell[] = [];
    for (const [date, info] of Object.entries(allCheckedInDates)) {
      if (info.checked) { // 只添加已签到的记录
        records.push({
          date: date,
          day: new Date(date).getDate(),
          inMonth: true,
          checkedIn: true, // 所有返回的记录都是已签到的
          isToday: false, // 这里不标记是否是今天
          disabled: false,
          points: info.points || 0 // 添加积分信息
        });
      }
    }
    
    // 按日期倒序排列（最新的在前面）
    records.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
    
    console.log('处理后的签到记录:', records); // 添加日志以便调试
    checkinRecordsList.value = records;
  } catch (error) {
    console.error('获取签到记录失败:', error);
    ElMessage.error('获取签到记录失败，请稍后重试');
  }
};

// 签到处理
const handleCheckin = async () => {
  try {
    const res = await userCheckin();
    console.log('签到接口返回数据:', res);
    // @ts-ignore
    if (res.code === 200) {
      const pointsEarned = res.data?.pointsEarned || 0;
      const consecutiveDays = res.data?.consecutiveDays || studyDays.value + 1;
      
      // 显示签到成功消息（只显示提示信息，不显示弹出卡片）
      ElMessage.success(`签到成功！获得 ${pointsEarned} 积分，连续签到 ${consecutiveDays} 天`);
      
      checkedInToday.value = true;
      studyDays.value = consecutiveDays;
      
      // 更新用户积分
      if (res.data && res.data.points !== undefined) {
        console.log('签到获得的积分:', res.data.points);
        userStore.setUserPoints(res.data.points);
      } else {
        console.warn('签到接口未返回积分数据');
      }
      
      // 重新获取学习数据和成就数据
      await Promise.all([
        fetchUserStudyData(),
        fetchAchievementsData()
      ]);
      
      // 重新生成签到日历以更新当天的签到状态
      await generateCalendar();
      
      // 更新签到记录列表
      await fetchAllCheckinRecords();
      

    } else {
      // @ts-ignore
      ElMessage.error(res.msg || '签到失败');
    }
  } catch (error) {
    console.error('签到异常:', error);
    ElMessage.error('签到失败，请稍后重试');
  }
};

// 成就详情对话框
const achievementsDialogVisible = ref(false);
const achievementsActiveTab = ref('earned');

// 计算已获得的成就
const earnedAchievements = computed(() => {
  return allAchievements.value.filter(achievement => achievement.earned === true);
});

// 显示成就详情对话框
const showAchievementsDialog = () => {
  achievementsDialogVisible.value = true;
};

// 跳转到成就页面（已废弃）
// const goToAchievements = () => {
//   router.push('/achievements');
// };

// 编辑资料相关
const editDialogVisible = ref(false);
const editFormRef = ref<FormInstance>();
const editForm = ref({
  userId: '',
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: ''
});

const editRules = reactive<FormRules>({
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度应在2-20个字符之间', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
});

// 头像上传相关
const avatarInputRef = ref<HTMLInputElement | null>(null);
const selectedAvatarFile = ref<File | null>(null);
const avatarUploading = ref(false);
const tempAvatarUrl = ref<string | null>(null);
const defaultAvatar = ref(''); // 默认头像URL，使用Element Plus的User图标作为默认头像

// 触发头像上传文件选择
const triggerAvatarUpload = () => {
  if (avatarInputRef.value) {
    avatarInputRef.value.click();
  }
};

// 处理头像文件选择
const handleAvatarFileSelect = (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    const file = input.files[0];
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请选择图片文件');
      return;
    }
    
    // 验证文件大小 (最大2MB)
    if (file.size > 2 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过2MB');
      return;
    }
    
    selectedAvatarFile.value = file;
    
    // 预览选中的图片
    const reader = new FileReader();
    reader.onload = (e) => {
      tempAvatarUrl.value = e.target?.result as string;
    };
    reader.readAsDataURL(file);
  }
};

// 上传头像
const uploadAvatar = async () => {
  if (!selectedAvatarFile.value) {
    ElMessage.warning('请先选择头像文件');
    return;
  }
  
  avatarUploading.value = true;
  try {
    // 上传头像时指定模块为"用户头像"
    const response = await uploadImage(selectedAvatarFile.value, '用户头像');
    // @ts-ignore
    if (response.code === 200) {
      // @ts-ignore
      const avatarUrl = response.data?.accessUrl || response.accessUrl;
      if (avatarUrl) {
        // 更新表单中的头像URL
        editForm.value.avatar = avatarUrl;
        ElMessage.success('头像上传成功');
        // 清除已选择的文件
        selectedAvatarFile.value = null;
        if (avatarInputRef.value) {
          avatarInputRef.value.value = '';
        }
      } else {
        ElMessage.error('头像上传失败：未获取到图片URL');
      }
    } else {
      // @ts-ignore
      ElMessage.error(response.msg || '头像上传失败');
    }
  } catch (error) {
    console.error('头像上传错误:', error);
    ElMessage.error('头像上传失败，请稍后重试');
  } finally {
    avatarUploading.value = false;
  }
};

// 编辑资料
const editProfile = () => {
  // 初始化表单数据
  if (currentUser.value) {
    editForm.value = {
      userId: currentUser.value.userId || '',
      username: currentUser.value.username || '',
      nickname: currentUser.value.nickname || '',
      email: currentUser.value.email || '',
      phone: currentUser.value.phone || '',
      avatar: currentUser.value.avatar || '' // 添加头像字段
    };
    // 重置头像上传状态
    tempAvatarUrl.value = null;
    selectedAvatarFile.value = null;
    if (avatarInputRef.value) {
      avatarInputRef.value.value = '';
    }
  }
  editDialogVisible.value = true;
};

// 保存资料
const saveProfile = async () => {
  if (!editFormRef.value) return;
  
  try {
    await editFormRef.value.validate();
    
    // 调用API更新用户信息
    const res = await updateUser(editForm.value);
    // @ts-ignore
    if (res.code === 200) {
      ElMessage.success('资料更新成功！');
      
      // 更新store中的用户信息
      userStore.setUserInfo({
        ...currentUser.value,
        ...editForm.value
      });
      
      // 添加：触发全局事件通知其他组件用户信息已更新
      console.log('触发用户信息更新事件，更新数据:', {
        ...currentUser.value,
        ...editForm.value
      });
      window.dispatchEvent(new CustomEvent('user-info-updated', {
        detail: {
          ...currentUser.value,
          ...editForm.value
        }
      }));
      
      // 关闭对话框
      editDialogVisible.value = false;
      
      // 重新获取学习数据
      await fetchUserStudyData();
    } else {
      // @ts-ignore
      ElMessage.error(res.msg || '更新失败');
    }
  } catch (error) {
    console.error('保存资料失败:', error);
    ElMessage.error('保存资料失败，请稍后重试');
  }
};

// 领取积分
const claimAchievementPoints = async (userAchievementId: number) => {
  try {
    // @ts-ignore
    const res = await claimAchievementPointsApi(userAchievementId);
    // @ts-ignore
    if (res.code === 200) {
      ElMessage.success('积分领取成功！');
      
      // 重新获取成就数据
      await fetchAchievementsData();
      
      // 更新用户积分显示
      await fetchUserStudyData();
    } else {
      // @ts-ignore
      ElMessage.error(res.msg || '领取失败');
    }
  } catch (error) {
    console.error('领取积分失败:', error);
    ElMessage.error('领取积分失败，请稍后重试');
  }
};

// 处理积分领取事件
const handlePointsClaimed = (points: number) => {
  // 更新用户积分
  userStore.setUserPoints(points);
  
  // 重新获取学习数据和成就数据
  fetchUserStudyData();
  fetchAchievementsData();
};

// 添加日历相关数据
const currentYear = ref(new Date().getFullYear());
const currentMonth = ref(new Date().getMonth() + 1);
const calendarDays = ref<DayCell[]>([]);

interface DayCell {
  date: string;
  day: number;
  inMonth: boolean;
  checkedIn: boolean;
  isToday: boolean;
  disabled: boolean;
}

// 获取月度签到记录的函数
const getMonthlyCheckinRecords = async (year: number, month: number) => {
  try {
    // 调用后端API获取真实的签到数据
    const response = await fetchMonthlyCheckinRecordsApi(year, month);
    return response;
  } catch (error) {
    console.error('获取月度签到记录失败:', error);
    // 如果API调用失败，返回模拟数据作为后备
    const today = new Date();
    const todayStr = today.toISOString().split('T')[0];
    
    // 生成模拟的签到数据
    const dateStatusMap: Record<string, boolean> = {};
    
    // 模拟最近30天内的签到记录
    for (let i = 0; i < 30; i++) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const dateStr = date.toISOString().split('T')[0];
      
      // 随机生成签到状态（70%概率已签到）
      dateStatusMap[dateStr] = Math.random() > 0.3;
    }
    
    return {
      code: 200,
      data: {
        dateStatus: dateStatusMap,
        checkinDays: Object.values(dateStatusMap).filter(status => status).length,
        totalDays: new Date(year, month, 0).getDate()
      }
    };
  }
};

// 生成日历数据
const generateCalendar = async () => {
  try {
    // 获取当月签到记录
    const res: any = await getMonthlyCheckinRecords(currentYear.value, currentMonth.value);
    if (res.code === 200 && res.data) {
      const dateStatusMap = res.data.dateStatus || {};
      
      const year = currentYear.value;
      const month = currentMonth.value;
      
      // 获取当月第一天是星期几（0-6，0表示星期日）
      const firstDayOfMonth = new Date(year, month - 1, 1).getDay();
      
      // 获取当月天数
      const daysInMonth = new Date(year, month, 0).getDate();
      
      const days: DayCell[] = [];
      const today = new Date();
      const todayDateStr = today.toISOString().split('T')[0];
      
      // 添加上个月的日期填充第一周
      const prevMonthYear = month === 1 ? year - 1 : year;
      const prevMonth = month === 1 ? 12 : month - 1;
      const daysInPrevMonth = new Date(prevMonthYear, prevMonth, 0).getDate();
      
      for (let i = 0; i < firstDayOfMonth; i++) {
        const day = daysInPrevMonth - firstDayOfMonth + i + 1;
        const dateStr = `${prevMonthYear}-${String(prevMonth).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
        
        days.push({
          date: dateStr,
          day,
          inMonth: false,
          checkedIn: false,
          isToday: false,
          disabled: true
        });
      }
      
      // 添加当月的日期
      for (let i = 1; i <= daysInMonth; i++) {
        const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(i).padStart(2, '0')}`;
        const isToday = dateStr === todayDateStr;
        
        days.push({
          date: dateStr,
          day: i,
          inMonth: true,
          checkedIn: dateStatusMap[dateStr] || false,
          isToday,
          disabled: new Date(dateStr) > today
        });
      }
      
      // 添加下个月的日期填充最后一周（仅显示空单元格）
      const remainingCells = 42 - days.length; // 6行7列的日历
      
      for (let i = 1; i <= remainingCells; i++) {
        days.push({
          date: `empty-${i}`,
          day: i,
          inMonth: false,
          checkedIn: false,
          isToday: false,
          disabled: true
        });
      }
      
      calendarDays.value = days;
      
      // 不再更新checkinRecordsList，保持显示所有记录
      // checkinRecordsList.value = days.filter(day => day.inMonth && !day.disabled);
    }
  } catch (error) {
    console.error('生成日历失败:', error);
  }
};

// 上个月
const prevMonth = () => {
  if (currentMonth.value === 1) {
    currentYear.value--;
    currentMonth.value = 12;
  } else {
    currentMonth.value--;
  }
  generateCalendar();
  // 不再重新获取签到记录，保持显示所有记录
  // await fetchAllCheckinRecords();
};

// 下个月
const nextMonth = () => {
  if (currentMonth.value === 12) {
    currentYear.value++;
    currentMonth.value = 1;
  } else {
    currentMonth.value++;
  }
  generateCalendar();
  // 不再重新获取签到记录，保持显示所有记录
  // await fetchAllCheckinRecords();
};

// 监听年月变化，重新生成日历，但不重新获取签到记录
watch([currentYear, currentMonth], () => {
  generateCalendar();
  // 不再重新获取签到记录，保持显示所有记录
  // await fetchAllCheckinRecords();
});

// 组件挂载时获取数据
onMounted(async () => {
  await nextTick();
  
  // 检查登录状态
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  
  // 初始化用户积分
  userStore.initUserPoints();
  console.log('用户积分初始值:', userStore.userPoints);
  
  // 获取学习数据和成就数据
  await Promise.all([
    fetchUserStudyData(),
    fetchAchievementsData()
  ]);
  
  // 生成签到日历
  await generateCalendar();
  
  // 获取所有签到记录（只在初始化时获取一次）
  await fetchAllCheckinRecords();
  
  console.log('用户积分更新后:', userStore.userPoints);
});

</script>

<style scoped>
.user-profile-container {
  padding: 0;
  margin: 0;
  min-height: 100vh;
  background: white;
  position: relative;
  overflow: hidden;
}

/* 统一白色背景内容区域 */
.profile-content {
  background: white;
  padding: 0;
  border-radius: 0;
  box-shadow: none;
  position: relative;
  z-index: 1;
}

/* 用户信息区域 */
.user-info-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  margin-bottom: 0;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8edf3 100%);
  border-radius: 0;
  border: none;
  border-bottom: 1px solid #e4e7ed;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-details h2 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 700;
  color: #1a1a1a;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.user-email {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.user-email::before {
  content: '✉️';
  font-size: 14px;
}

.user-points {
  color: #667eea;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: rgba(102, 126, 234, 0.1);
  border-radius: 20px;
  width: fit-content;
}

.user-actions {
  display: flex;
  gap: 8px;
}

/* 内容区域 */
.section-content {
  padding: 24px;
  margin-bottom: 0;
  background: white;
  border-radius: 0;
  border: none;
  border-bottom: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.section-content:hover {
  background: #fafbfc;
}

.section-content:not(:last-child) {
  border-bottom: none;
}

.section-content:first-child {
  padding-top: 24px;
}

.section-content:last-child {
  padding-bottom: 24px;
  border-bottom: none;
}

.section-content h3 {
  font-size: 20px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0 0 20px 0;
  padding-bottom: 12px;
  border-bottom: 3px solid #667eea;
  display: inline-block;
}

/* 成就标题和按钮区域 */
.achievements-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.achievements-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.view-all-achievements {
  padding: 6px 12px;
  font-size: 12px;
}

/* 统计网格 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px 16px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12px;
  border: 2px solid #e4e7ed;
  transition: all 0.3s ease;
  cursor: pointer;
}

.stat-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.15);
  border-color: #667eea;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

/* 签到按钮 */
.checkin-button {
  padding: 8px 20px;
  font-weight: 600;
  font-size: 14px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.checkin-button:not(.checked-button) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.checkin-button:not(.checked-button):hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.checked-button {
  background: linear-gradient(135deg, #67c23a 0%, #4caf50 100%);
  border: none;
}

/* 题目列表 */
.module-questions-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  padding: 0;
}

.module-question-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: white;
  border-radius: 8px;
  border: 2px solid #e4e7ed;
  transition: all 0.3s ease;
}

.module-question-item:hover {
  border-color: #667eea;
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
}

.module-name {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.module-count {
  font-size: 16px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

/* 进度网格 */
.progress-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.progress-item {
  padding: 20px;
  background: white;
  border-radius: 12px;
  border: 2px solid #e4e7ed;
  transition: all 0.3s ease;
}

.progress-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: #667eea;
}

.module-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.module-name {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
}

.progress-text {
  font-size: 13px;
  color: #666;
  margin-top: 10px;
  text-align: right;
  font-weight: 500;
}

/* 成就概览 */
.achievements-summary {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.achievement-stats {
  display: flex;
  gap: 16px;
  padding: 0;
}

.achievement-stats .stat-item {
  display: flex;
  align-items: center;
  background: white;
  padding: 16px 20px;
  gap: 12px;
  min-width: 140px;
  border-radius: 12px;
  border: 2px solid #e4e7ed;
  flex-direction: row;
}

.achievement-stats .stat-item:hover {
  border-color: #667eea;
}

.recent-achievements h4,
.all-achievements h4 {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 16px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #e4e7ed;
}

.achievement-list {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

/* 空状态样式 */
.empty-achievements {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #909399;
  background: #f8f9fa;
  border-radius: 12px;
  margin-top: 16px;
}

.empty-achievements .empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.empty-achievements p {
  margin: 0;
  font-size: 14px;
}

/* 成就网格布局 */
.achievement-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 20px;
  padding: 10px;
}

.achievement-section {
  min-height: 200px;
}

.achievement-section .empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #909399;
}

.achievement-section .empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
}

.achievement-section .empty-state p {
  margin: 0;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-profile-container {
    padding: 0;
  }
  
  .profile-content {
    padding: 0;
    border-radius: 0;
  }
  
  .user-info-section {
    flex-direction: column;
    gap: 16px;
    text-align: center;
    padding: 20px;
  }
  
  .avatar-section {
    flex-direction: column;
  }
  
  .user-actions {
    width: 100%;
    justify-content: center;
  }
  
  .section-content {
    padding: 20px;
  }
  
  .achievements-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .stat-item {
    padding: 16px 12px;
  }
  
  .stat-value {
    font-size: 24px;
  }
  
  .module-questions-list {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  
  .module-question-item {
    width: 100%;
    justify-content: space-between;
    padding: 10px 14px;
  }
  
  .progress-grid {
    grid-template-columns: 1fr;
  }
  
  .achievement-stats {
    flex-direction: column;
    gap: 12px;
  }
  
  .achievement-stats .stat-item {
    width: 100%;
    padding: 12px 16px;
  }
  
  .achievement-list {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .checkin-calendar-section {
    max-width: 100%;
  }
}

@media (max-width: 480px) {
  .user-profile-container {
    padding: 0;
  }
  
  .profile-content {
    padding: 0;
  }
  
  .user-info-section {
    padding: 16px;
  }
  
  .section-content {
    padding: 16px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  
  .stat-item {
    padding: 12px 10px;
  }
  
  .stat-value {
    font-size: 24px;
  }
  
  .section-content h3 {
    font-size: 18px;
  }
  
  .user-details h2 {
    font-size: 24px;
  }
}

/* 头像上传样式 */
.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
}

.avatar-preview {
  margin-bottom: 6px;
}

.avatar-upload-controls {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.file-info {
  font-size: 11px;
  color: #666;
  margin-top: 4px;
}

/* 签到日历样式 */
.checkin-calendar-section {
  padding: 20px;
  background: white;
  border-radius: 12px;
  border: 2px solid #e4e7ed;
  max-width: 400px;
  margin: 0;
}

.calendar-header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e4e7ed;
}

.calendar-header-section h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: #1a1a1a;
}

.calendar-nav {
  display: flex;
  align-items: center;
  gap: 12px;
}

.current-month {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  min-width: 100px;
  text-align: center;
}

.month-arrow {
  color: #667eea;
  font-size: 16px;
  padding: 4px;
  transition: all 0.3s ease;
}

.month-arrow:hover {
  color: #764ba2;
  transform: scale(1.2);
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  margin-bottom: 8px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8edf3 100%);
  border-radius: 8px;
  padding: 8px 0;
}

.weekday {
  text-align: center;
  font-size: 13px;
  color: #666;
  padding: 4px 0;
  font-weight: 600;
}

.days-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
}

.day-cell {
  aspect-ratio: 1;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  border: 2px solid #ebeef5;
  font-size: 14px;
  background-color: #ffffff;
  transition: all 0.3s ease;
  cursor: pointer;
}

.day-cell:hover:not(.empty):not(.disabled) {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.day-cell.empty {
  background-color: #fafafa;
  border-color: #f5f5f5;
}

.day-cell.checked {
  background: linear-gradient(135deg, #e8f0ff 0%, #d4e5ff 100%);
  border-color: #667eea;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

.day-cell.today {
  border: 2px solid #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.day-cell.disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.day-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.day-number {
  font-size: 15px;
  font-weight: 600;
  color: #333;
}

.check-icon {
  color: #52c41a;
  font-size: 10px;
  position: absolute;
  top: 2px;
  right: 2px;
  background: white;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}



/* 签到记录列表样式 */
.checkin-records-table {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.checkin-records-table :deep(.el-table__cell) {
  text-align: center;
  padding: 12px 0;
}

.checkin-records-table :deep(.el-table__header) {
  background: linear-gradient(135deg, #f5f7fa 0%, #e8edf3 100%);
}

.checkin-records-table :deep(.el-table__header th) {
  background: transparent;
  font-weight: 600;
  color: #1a1a1a;
}

.checkin-records-table :deep(.el-table__row:hover) {
  background: #f8f9fa;
}

.table-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.table-pagination :deep(.el-pagination.is-background .el-pager li:not(.disabled).is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

/* 积分值样式 */
.points-value {
  font-weight: 700;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  font-size: 15px;
}
</style>